<?php

namespace longhu\services;


use longhu\event\LoadModuleRoutes;
use longhu\MyAdmin;
use longhu\MyExceptionHandle;
use longhu\MyShopConsole;
use think\exception\Handle;
use think\Service;

/**
 * 基础注册服务
 */
class MyshopBaseService extends Service
{

    //注册
    public function boot()
    {}

    public function register()
    {
        $this->registerCommands();
        $this->registerEvents();
        $this->registerExceptionHandle();
        $this->registerRoutePath();
        $this->registerServices();
       // dump(23234);exit;


    }


    /**
     * 注册命令行
     * @return void
     */
    public function registerCommands()
    {
        if($this->app->runningInConsole()){
            $catchConsole = new MyShopConsole($this->app);
            $this->app->bind('app\console', $catchConsole);
            $this->commands($catchConsole->defaultCommands());
        }
    }

    //注册验证类
    public function registerValidates()
    {

    }

    /**
     * 注册监听者
     * @time 2019年12月12日
     * @return void
     */
    protected function registerEvents(): void
    {
        $this->app->event->listenEvents([
            'RouteLoaded' => [LoadModuleRoutes::class]
        ]);
    }

    /**
     * register exception
     *
     * @time 2020年02月20日
     * @return void
     */
    protected function registerExceptionHandle(): void
    {
        $this->app->bind(Handle::class, MyExceptionHandle::class);
    }


    /**
     * 注册模块服务
     *
     * @time 2020年06月23日
     * @return void
     */
    protected function registerServices()
    {
        $services = file_exists(MyAdmin::getCacheServicesFile()) ?
            include MyAdmin::getCacheServicesFile() :
            MyAdmin::getEnabledService();
        foreach ($services as $service) {
            if (class_exists($service)) {
                $this->app->register($service);
            }
        }
    }


    /**
     * 注册路由地址
     *
     * @time 2023年06月23日
     * @return void
     */
    protected function registerRoutePath()
    {
//        if(env('ANNOTATION')){
//            $annotationConfig = config('annotation');
//            //dump($annotationConfig);exit;
//            $route = $annotationConfig['route'];
//            $controllers = $route['controllers'];
//            // 获取
//        }
        $this->app->instance('routePath', new class {
            protected $path = [];
            public function loadRouterFrom($path)
            {
                $this->path[] = $path;
                return $this;
            }
            public function get()
            {
                return $this->path;
            }
        });
    }
}